import React, { Component } from 'react';
import { FlatList, Image, Text, View, StyleSheet, Alert } from 'react-native';
import axios from 'axios'

export default class App extends Component {

  state = {
    data: [],
    loaded: false,
    limit: 10,
    page: 1,
    ismore: true
  }

  startSocket() {
    const ws = new WebSocket('ws://192.168.2.1:8081')
    ws.onopen = () => {
      ws.send('hello')
    }
    ws.onmessage = (msg) => {
      console.log(msg)
      alert(msg.data)
    }
    ws.onerror =()=>{
    }
    ws.onclose=()=>{
    }
  }

  componentDidMount() {
    // this.fetchData()
    this.fetchDataByAxios();
    this.startSocket();
  }

  fetchData() {

    fetch(`http://192.168.2.1:9099/coming?_limit=${this.state.limit}&_page=${this.state.page}`).then((response) => response.json())
      .then((result) => {
        console.log(result.length);
        this.setState({
          data: this.state.data.concat(result),
          loaded: true,
          ismore: result.length === this.state.limit ? true : false
        })
      })
  }

  async fetchDataByAxios() {
    let result = await axios.get(`http://192.168.2.1:9099/coming?_limit=${this.state.limit}&_page=${this.state.page}`)

    console.log('result:', result.data.length);
    this.setState({
      data: this.state.data.concat(result.data),
      loaded: true,
      ismore: result.data.length === this.state.limit ? true : false
    })


  }

  renderLoadingView() {
    return (
      <View style={styles.container}>
        <Text> loading movies ....</Text>
      </View>
    )
  }

  renderMovieItem({ item }) {
    return (
      <View style={styles.ItemContainer}>
        <Image style={styles.img} source={{ uri: item.img.replace('w.h', '100.150') }}></Image>
        <View style={styles.rigthContainer}>
          <Text>{item.nm}</Text>
        </View>
      </View>
    )
  }

  render() {
    if (!this.state.loaded) {
      return this.renderLoadingView()
    }

    return (
      <View style={styles.container}>
        <FlatList data={this.state.data}
          renderItem={this.renderMovieItem}
          onEndReachedThreshold={0.2}
          onEndReached={() => {
            console.log('reach end')

            if (!this.state.ismore) {
              Alert.alert('')
              Alert.alert(
                '提示',
                '没有更多的数据了',
                [
                  { text: 'OK', onPress: () => console.log('OK Pressed') },
                ],
                { cancelable: false }
              )
              return;
            }

            this.setState({
              page: this.state.page + 1
            }, () => {
              // this.fetchData()
              this.fetchDataByAxios();
            })
          }}
        >
        </FlatList>
      </View>
    )

  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 5
    // alignItems: "center"
  },
  ItemContainer: {
    flex: 1,
    flexDirection: "row",
    marginTop: 5

  },
  rigthContainer: {
    marginLeft: 5,
    backgroundColor: '#efefef',
    flex: 1
  },
  img: {
    width: 100,
    height: 150
  }
})